import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi/locale';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Card,
  InputNumber,
  Radio,
  Icon,
  Tooltip,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './ArticleForm.less';

import E from 'wangeditor'


const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;

const linePath = '/articles/article'


@connect(({ article, loading }) => ({
  article,
  submitting: loading.effects['form/submitRegularForm'],
}))
@Form.create()
class BasicForms extends PureComponent {
  constructor(props, context) {
      super(props, context);
      this.state = {
        editorContent: '',
        editor: null,
        record: {},
        idEdit: false,
      }
  }

  async componentDidMount() {
    const elem = this.refs.editorElem
    const editor = new E(elem)
    editor.customConfig.uploadImgShowBase64 = true
    // 使用 onchange 函数监听内容的变化，并实时更新到 state 中
    editor.customConfig.onchange = html => {
      this.setState({
        editorContent: html
      })
    }
    editor.create()
    this.setState({
        editor
    })

    const { dispatch } = this.props;
    const { location: {query: { id } } } = this.props;
    if (id) {
      await dispatch({
        type: 'article/view',
        payload:  { id: Number(id) }
      });

      const { article: { record } } = this.props;
      this.setState({
        record, idEdit: true
      })

      editor.txt.html(record.notes)
      this.setState({
        editorContent: record.notes
      })


    }
  }


  handleSubmit = e => {
    const { dispatch, form } = this.props;
    e.preventDefault();
    form.validateFieldsAndScroll( async (err, values) => {
      if (!err) {
//          alert(this.state.editorContent)
          const { location: {query: { id } } } = this.props;
          console.log( this.state.editorContent )

          const { dispatch } = this.props;
          const vals = {
             notes: this.state.editorContent,
             ...values,
          }

          if (id) {
            await dispatch({
               type: 'article/write',
               payload : {id: Number(id), vals } ,
            });
          }
          else{
            await dispatch({
              type: 'article/create',
              payload: { vals: { ...vals, state: 'draft' } } ,
            });
          }

          const redir = `${linePath}?id=${this.props.article.record.id}`
          this.props.history.push(redir)
      }
    });
  };

  render() {
    const { submitting } = this.props;
    const {
      form: { getFieldDecorator, getFieldValue },
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const {record} = this.state

    return (
      <PageHeaderWrapper
        title={'新建稿件'}
        content={'请先录入稿件的基本信息, 稍后可以编辑文章内容'}
      >
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
            <FormItem {...formItemLayout} label={'标题'}>
              {getFieldDecorator('title', {
                rules: [
                  {
                    //required: true,
                    message: formatMessage({ id: 'validation.title.required' }),
                  },
                ],
                initialValue: record.title,
              })(<Input placeholder={'文章标题'} />)}
            </FormItem>

            <FormItem {...formItemLayout} label={'作者'}>
              {getFieldDecorator('owner', {
                rules: [
                  {
                    //required: true,
                    message: '需要写上作者',
                  },
                ],
                initialValue: record.owner,
              })(<Input placeholder={'作者'} />)}
            </FormItem>



            <FormItem {...formItemLayout} label='简介'>
              {getFieldDecorator('content', {
                rules: [
                  {
                    required: true,
                    message: '文章简介',
                  },
                ],
                initialValue: record.content,
              })(
                <TextArea
                  style={{ minHeight: 32 }}
                  placeholder='文章简介'
                  rows={4}
                />
              )}
            </FormItem>


            <FormItem
              {...formItemLayout}
              label={'标签:'}


            >
                  {getFieldDecorator('tags',{
                    initialValue: record.tags,

                  })(
                    <Select
                      mode="multiple"
                      placeholder={'选择文章的标签'}
                      style={{
                        margin: '8px 0',
                      }}
                    >
                      <Option value="政策">
                        政策
                      </Option>
                      <Option value="通知">
                        通知
                      </Option>
                      <Option value="市场">
                        市场
                      </Option>
                    </Select>
                  )}
            </FormItem>


            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" htmlType="submit" loading={submitting}>
                <FormattedMessage id="form.submit" />
              </Button>
              <Button style={{ marginLeft: 8 }}>
                <FormattedMessage id="form.save" />
              </Button>
            </FormItem>
          </Form>


          {/* 将生成编辑器 */}
          <div ref="editorElem" style={{textAlign: 'left'}}>
          </div>


        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default BasicForms;
